<template>
  <div class="center-map-container">
    <!-- 地图标题 -->
    <div class="map-header">
      <!-- <h3 class="map-title">{{ regionName }}区域规划地图</h3> -->
      <div class="map-controls">
        <el-button-group>
          <el-button 
            :type="currentView === 'overview' ? 'primary' : 'default'"
            size="small"
            @click="switchView('overview')"
          >
            总览
          </el-button>
          <el-button 
            :type="currentView === 'planning' ? 'primary' : 'default'"
            size="small"
            @click="switchView('planning')"
          >
            规划区域
          </el-button>
          <el-button 
            :type="currentView === 'facilities' ? 'primary' : 'default'"
            size="small"
            @click="switchView('facilities')"
          >
            设施分布
          </el-button>
        </el-button-group>
      </div>
    </div>
    
    <!-- 地图容器 -->
    <div class="map-wrapper">
      <div ref="mapRef" class="map-chart"></div>
      
      <!-- 地图图例 -->
      <div class="map-legend">
        <div class="legend-item" v-for="item in legendData" :key="item.name">
          <span class="legend-color" :style="{ backgroundColor: item.color }"></span>
          <span class="legend-text">{{ item.name }}</span>
        </div>
      </div>
    </div>
    
    <!-- 地图信息面板 -->
    <div class="map-info-panel" v-if="selectedRegion">
      <div class="panel-header">
        <h4>{{ selectedRegion.name }}</h4>
        <el-button size="small" text @click="closeInfoPanel">
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
      <div class="panel-content">
        <div class="info-item">
          <span class="info-label">区域代码:</span>
          <span class="info-value">{{ selectedRegion.adcode }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">中心坐标:</span>
          <span class="info-value">{{ selectedRegion.center.join(', ') }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">规划类型:</span>
          <span class="info-value">{{ selectedRegion.planningType }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">建设状态:</span>
          <span class="info-value">{{ selectedRegion.status }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElButton, ElButtonGroup, ElIcon } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import { qingyunMapData, getRegionCenter, getRegionName, getAdcode } from '@/utils/qingyun'
import type { GeoJSONFeatureCollection } from '@/utils/qingyun'

// 地图实例
const mapRef = ref<HTMLElement | null>(null)
let mapInstance: echarts.ECharts | null = null

// 当前视图模式
const currentView = ref<'overview' | 'planning' | 'facilities'>('overview')

// 区域信息
const regionName = ref(getRegionName())
const selectedRegion = ref<any>(null)

// 图例数据
const legendData = ref([
  { name: '三农中心', color: '#7CBDCF' },
  { name: '物流园', color: '#5287DE' },
  { name: '党校', color: '#52C41A' },
  { name: '环保局', color: '#FAAD14' },
])

// 模拟设施数据
const facilitiesData = [
  { name: '三农中心', value: [117.390507, 37.777724, 100], type: 'green-power', status: '运行中' },
  { name: '物流园', value: [117.420507, 37.787724, 80], type: 'charging', status: '建设中' },
  { name: '数据中心C', value: [117.360507, 37.767724, 120], type: 'datacenter', status: '规划中' },
  { name: '党校', value: [117.450507, 37.797724, 90], type: 'green-power', status: '运行中' },
  { name: '充环保局电站E', value: [117.380507, 37.757724, 70], type: 'charging', status: '运行中' }
]

// 规划区域数据
const planningData: any[] = [
//   { name: '核心发展区', center: [117.390507, 37.777724], planningType: '综合发展', status: '建设中' },
//   { name: '绿色能源区', center: [117.420507, 37.787724], planningType: '新能源', status: '规划中' },
//   { name: '智慧物流区', center: [117.360507, 37.767724], planningType: '物流枢纽', status: '运行中' }
]
const timer = ref()
// 初始化地图
const initMap = async () => {
  if (!mapRef.value) return
  
  // 注册地图数据
  echarts.registerMap('qingyun', qingyunMapData as any)
  
  // 创建地图实例
  mapInstance = echarts.init(mapRef.value)
  
  // 设置地图配置
  timer.value = setInterval(() => {
    updateMapOption()
    clearTimeout(timer.value)
  }, 1000)
  
  // 添加点击事件
  mapInstance.on('click', handleMapClick)
}

// 更新地图配置
const updateMapOption = () => {
  if (!mapInstance) return
  
  const option: echarts.EChartsOption = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: 'rgba(124, 189, 207, 0.8)',
      textStyle: {
        color: '#ffffff'
      },
      formatter: function(params: any) {
        if (params.seriesType === 'map') {
          return `${params.name}<br/>区域代码: ${getAdcode()}`
        } else if (params.seriesType === 'scatter') {
          return `${params.name}<br/>类型: ${params.data.type}<br/>状态: ${params.data.status}<br/>数值: ${params.data.value[2]}`
        }
        return params.name
      }
    },
    geo: {
      map: 'qingyun',
      roam: true,
      zoom: 1,
      center: getRegionCenter(),
      itemStyle: {
        areaColor: 'rgba(124, 189, 207, 0.1)',
        borderColor: '#7CBDCF',
        borderWidth: 2
      },
      emphasis: {
        itemStyle: {
          areaColor: 'rgba(124, 189, 207, 0.3)'
        }
      },
      label: {
        show: true,
        color: '#ffffff',
        fontSize: 14,
        fontWeight: 'bold'
      }
    },
    series: getSeries()
  }
  
  mapInstance.setOption(option)
}

// 获取系列数据
const getSeries = () => {
  const series: any[] = []
  
  // 基础地图
  series.push({
    type: 'map',
    map: 'qingyun',
    geoIndex: 0,
    data: [{
      name: regionName.value,
      value: getAdcode()
    }]
  })
  
  // 根据当前视图添加不同的数据层
  if (currentView.value === 'facilities' || currentView.value === 'overview') {
    // 设施散点图
    series.push({
      type: 'scatter',
      coordinateSystem: 'geo',
      data: facilitiesData.map(item => ({
        ...item,
        symbolSize: item.value[2] / 5,
        itemStyle: {
          color: getFacilityColor(item.type)
        }
      })),
      symbol: 'circle',
      symbolSize: function(val: any) {
        return Math.max(val[2] / 5, 8)
      },
      label: {
        show: true,
        position: 'right',
        color: '#ffffff',
        fontSize: 10,
        formatter: '{b}'
      },
      emphasis: {
        scale: true,
        scaleSize: 1.5
      }
    })
  }
  
  if (currentView.value === 'planning' || currentView.value === 'overview') {
    // 规划区域效果圆
    series.push({
      type: 'effectScatter',
      coordinateSystem: 'geo',
      data: planningData.map(item => ({
        name: item.name,
        value: [...item.center, 50],
        planningType: item.planningType,
        status: item.status
      })),
      symbolSize: 20,
      showEffectOn: 'render',
      rippleEffect: {
        brushType: 'stroke',
        scale: 2.5,
        period: 4
      },
      itemStyle: {
        color: '#5287DE',
        shadowBlur: 10,
        shadowColor: '#5287DE'
      },
      label: {
        show: true,
        position: 'bottom',
        color: '#ffffff',
        fontSize: 10,
        formatter: '{b}'
      }
    })
  }
  
  return series
}

// 获取设施颜色
const getFacilityColor = (type: string) => {
  const colorMap: Record<string, string> = {
    'green-power': '#52C41A',
    'charging': '#FAAD14',
    'datacenter': '#F5222D'
  }
  return colorMap[type] || '#7CBDCF'
}

// 切换视图
const switchView = (view: 'overview' | 'planning' | 'facilities') => {
  currentView.value = view
  updateMapOption()
}

// 处理地图点击事件
const handleMapClick = (params: any) => {
  if (params.seriesType === 'effectScatter') {
    // 点击规划区域
    const planningItem = planningData.find(item => item.name === params.name)
    if (planningItem) {
      selectedRegion.value = {
        name: planningItem.name,
        adcode: getAdcode(),
        center: planningItem.center,
        planningType: planningItem.planningType,
        status: planningItem.status
      }
    }
  } else if (params.seriesType === 'scatter') {
    // 点击设施点
    const facility = facilitiesData.find(item => item.name === params.name)
    if (facility) {
      selectedRegion.value = {
        name: facility.name,
        adcode: getAdcode(),
        center: [facility.value[0], facility.value[1]],
        planningType: facility.type,
        status: facility.status
      }
    }
  }
}

// 关闭信息面板
const closeInfoPanel = () => {
  selectedRegion.value = null
}

// 窗口大小变化处理
const handleResize = () => {
  if (mapInstance) {
    mapInstance.resize()
  }
}

// 生命周期
onMounted(async () => {
  await nextTick()
  setTimeout(()=>{
      initMap()
    },1000)
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (mapInstance) {
    mapInstance.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="less" scoped>
.center-map-container {
  width: 100%;
  height: 100%;
  position: relative;
  background: linear-gradient(135deg, rgba(31, 99, 163, 0.1) 0%, rgba(124, 189, 207, 0.1) 100%);
  border-radius: 8px;
  overflow: hidden;
  
  .map-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background: rgba(0, 0, 0, 0.3);
    border-bottom: 1px solid rgba(124, 189, 207, 0.3);
    
    .map-title {
      margin: 0;
      color: #7EB7FD;
      font-size: 16px;
      font-weight: 600;
    }
    
    .map-controls {
      :deep(.el-button-group) {
        .el-button {
          background: rgba(124, 189, 207, 0.1);
          border-color: rgba(124, 189, 207, 0.3);
          color: #7EB7FD;
          
          &:hover {
            background: rgba(124, 189, 207, 0.2);
            border-color: #7CBDCF;
            color: #ffffff;
          }
          
          &.el-button--primary {
            background: #5287DE;
            border-color: #5287DE;
            color: #ffffff;
          }
        }
      }
    }
  }
  
  .map-wrapper {
    position: relative;
    width: 100%;
    height: calc(100% - 70px);
    
    .map-chart {
      width: 100%;
      height: 100%;
    }
    
    .map-legend {
      position: absolute;
      top: 20px;
      right: 20px;
      background: rgba(0, 0, 0, 0.7);
      padding: 15px;
      border-radius: 6px;
      border: 1px solid rgba(124, 189, 207, 0.3);
      
      .legend-item {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .legend-color {
          width: 12px;
          height: 12px;
          border-radius: 2px;
          margin-right: 8px;
        }
        
        .legend-text {
          color: #ffffff;
          font-size: 12px;
        }
      }
    }
  }
  
  .map-info-panel {
    position: absolute;
    bottom: 20px;
    left: 20px;
    width: 280px;
    background: rgba(0, 0, 0, 0.8);
    border: 1px solid rgba(124, 189, 207, 0.5);
    border-radius: 8px;
    overflow: hidden;
    
    .panel-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 15px;
      background: rgba(124, 189, 207, 0.2);
      border-bottom: 1px solid rgba(124, 189, 207, 0.3);
      
      h4 {
        margin: 0;
        color: #ffffff;
        font-size: 14px;
        font-weight: 600;
      }
      
      :deep(.el-button) {
        color: #7EB7FD;
        
        &:hover {
          color: #ffffff;
        }
      }
    }
    
    .panel-content {
      padding: 15px;
      
      .info-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .info-label {
          color: #7EB7FD;
          font-size: 12px;
        }
        
        .info-value {
          color: #ffffff;
          font-size: 12px;
          font-weight: 500;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .center-map-container {
    .map-header {
      flex-direction: column;
      gap: 10px;
      
      .map-title {
        font-size: 14px;
      }
    }
    
    .map-info-panel {
      width: calc(100% - 40px);
      bottom: 10px;
      left: 20px;
      right: 20px;
    }
    
    .map-legend {
      top: 10px;
      right: 10px;
      padding: 10px;
    }
  }
}
</style>